<%--
  Created by IntelliJ IDEA.
  User: leixiaolong
  Date: 2018/9/13
  Time: 下午6:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>入库单详情</title>
    <link rel="stylesheet" href="/static/css/rpt-condition.css" media="all" type="text/css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/plugins/layui/css/layui.css" media="all"
          type="text/css">
    <style>
        .layui-table-header {
            background-color: #1E9FFF;
        }

        .layui-table thead tr {
            background-color: #1E9FFF;
            color: black;
        }
    </style>

    <style>
        .layui-form-label {
            width: 160px !important;
        }
    </style>

    <style>
        /* 防止下拉框的下拉列表被隐藏---必须设置--- */
        .layui-table-cell {
            overflow: visible !important;
        }

        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select {
            /*margin-top: -10px;*/
            /*margin-left: -15px;*/
            /*margin-right: -15px;*/
            /*solid: #d2d2d2;*/
            /*border: 1px;*/
        }

        /* 设置下拉框的高度与表格单元相同 */
        .layui-input, .layui-select, .layui-textarea {
            height: 30px !important;
        }
    </style>

    <style>
        .col-select-lg {
            margin-top: 10px;
            height: 30px;
            width: 300px;
            min-width: 200px;
            max-width: 600px;
        }

        .layui-input-inline {
            min-width: 300px;
            max-width: 600px;
        }
    </style>
</head>
<body class="layui-bg-gray">
<div class="layui-row layui-col-space10" style="margin: 10px; background-color: white;">
    <div class="layui-container">
        <div class="layui-row layui-form">
            <div class="layui-col-md6 layui-hide">
                <div class="layui-form-item">
                    <label class="layui-form-label ">入库单id：</label>
                    <input type="text" id="txt_stock_id" class="layui-input-inline dom-add-input" readonly>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">仓库名称：</label>
                    <input type="text" id="txt_stor_name" class="layui-input-inline dom-add-input" readonly>
                    <%--<div class="layui-input-inline">--%>
                    <%--<select class="layui-form-select" id="sel_stor">--%>
                    <%--</select>--%>
                    <%--</div>--%>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">入库类型：</label>
                    <input type="text" id="txt_stockin_type" class="layui-input-inline dom-add-input" readonly>
                    <%--<div class="layui-input-inline">--%>
                    <%--<select class="layui-form-select" id="sel_stockin_type">--%>
                    <%--</select>--%>
                    <%--</div>--%>
                </div>
            </div>
            <%--<div class="layui-col-md6">--%>
            <%--<div class="layui-form-item layui-input-inline">--%>
            <%--<label class="layui-form-label">源单据类型</label>--%>
            <%--<div class="layui-input-inline">--%>
            <%--<select class="layui-form-select" id="sel_sour_type">--%>
            <%--</select>--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--</div>--%>
            <div class="layui-col-md6">
                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">入库日期：</label>
                    <input type="text" class="layui-input-inline dom-input" id="date_stockin"
                           placeholder="yyyy-MM-dd" disabled>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">源单据id</label>
                    <input type="text" id="txt_sour_id" class="layui-input-inline dom-add-input" readonly>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">摘要</label>
                    <input type="text" id="txt_digest" class="layui-input-inline dom-add-input" readonly>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-btn-container" style="float: right; margin-right: 5%;">
        <button class="layui-btn layui-btn-normal layui-bg-blue" lay-submit data-type="verfyPass">审核通过</button>
        <button class="layui-btn layui-btn-normal layui-bg-red" style="margin-left: 20px;" lay-submit
                data-type="verfyNopass">审核不通过
        </button>
    </div>

    <div>

    </div>
    <input type="text" id="txt_verfy_err_msg" class="layui-input-inline dom-add-input" style="float: right; margin-right: 10%;">
</div>

<div style="margin: 10px; background-color: white;">
    <table class="layui-hide" id="tab_data_content"></table>
</div>

</body>
</html>

<script language='javascript' src="${pageContext.request.contextPath}/plugins/layui/layui.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/comm-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/table-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-select.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-date.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/moment.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-math.js"></script>

<script>
    var recordNum = 0;
    var taxRate = 0;
    var gooddata = [];

    var initTable = async () => {
        var res = new Promise(function (resolve, reject) {
            layui.use(["table", "form", "jquery"], function () {
                var table = layui.table, form = layui.form, $ = layui.jquery;

                table.set({
                    limit: 50
                });
                var tableIns = table.render({
                    id: 'tab_data_content',
                    elem: '#tab_data_content',
                    // toolbar: '#toolbarAdd',
                    // defaultToolbar: [],
                    cellMinWidth: 90,
                    height: 'full-230',
                    cols: [[
                        {field: 'seqNo', title: '序号', type: 'numbers', align: 'center'},
                        {field: 'goodCode', title: '商品编码', align: 'center', hide: true},
                        {
                            field: 'goodName', title: '商品名称', minWidth: 140, align: 'center'
                            // field: 'goodName', title: '商品名称', minWidth: 140, templet: function (d) {
                            //     // return loadGoodSelect(d.seqNo, gooddata, d.goodCode);
                            //     return getGoodName(gooddata, d.goodCode);
                            // }, align: 'center'
                        },
                        {field: 'varietyCode', title: '品种编码', align: 'center', hide: true},
                        {field: 'varietyName', title: '品种名称', align: 'center', hide: true},
                        {field: 'standardName', title: '商品规格', align: 'center'},
                        {field: 'unit', title: '商品单位', align: 'center'},
                        {
                            field: 'price', title: '商品价格', edit: false, align: 'center', templet: function (d) {
                                if (typeof(d.price) == 'undefined') {
                                    return 0;
                                }
                                return getFloat(d.price);
                            }
                        },
                        {
                            field: 'amount', title: '商品数量', edit: false, align: 'center', templet: function (d) {
                                if (typeof(d.amount) == 'undefined') {
                                    return 0;
                                }
                                return getFloat(d.amount);
                            }
                        },
                        {
                            field: 'bal', title: '商品金额', edit: false, align: 'center', templet: function (d) {
                                if (typeof(d.price) == 'undefined' || typeof(d.amount) == 'undefined') {
                                    return 0;
                                }
                                return getFloat(d.price * d.amount);
                            }
                        },
                        {field: 'digest', title: '摘要', align: 'center', edit: false},
                        {
                            field: 'opertaor', title: '操作', align: 'center', templet: '#rowBar', fixed: 'right'
                        }
                    ]],
                    done: function () {
                        console.log("渲染表格 over");
                        form.render();
                    },
                    page: false
                });

                /**
                 * 监听表头工具bar事件
                 */
                table.on('toolbar', function (obj) {
                    switch (obj.event) {
                        case 'add':
                            layer.msg('添加');
                            var newdata = table.cache["tab_data_content"];
                            if (newdata == null || newdata == 'undefined') {
                                newdata = [];
                            }

                            var newline = {};
                            recordNum = newdata.length;
                            newline['seqNo'] = ++recordNum;

                            // newdata.unshift(newline);//左侧加入
                            newdata.push(newline);//右侧加入
                            table.reload('tab_data_content', {
                                url: null,
                                limit: 50,
                                data: newdata
                            });

                            loadGoodSelect(recordNum, gooddata);
                            form.render('select');
                            break;
                        default:
                            layer.msg("请等待功能开放");
                            break;
                    }
                });

                /**
                 * 监听表行工具bar事件
                 */
                table.on('tool', function (obj) {
                    //获得当前行数据
                    var rowdata = obj.data;
                    var layEvent = obj.event;//获得当前行事件
                    var tr = obj.tr;//获得当前行tr的dom对象

                    switch (layEvent) {
                        case 'del':
                            layer.confirm("是否删除本条记录", {icon: 3}, function (index) {
                                obj.del();
                                layer.close(index);
                            });
                            break;
                        default:
                            layer.msg("请等待功能开放");
                            break;
                    }

                    //同步更新缓存对应的值
                    // obj.update({username:'123', title: 'xxx'});
                });

                /**
                 * 监听select下拉框事件
                 */
                form.on('select', async function (data) {
                    //监听数据处理
                    var goodCode = data.value;

                    //获取当前行记录
                    var rowdata = await getRowItemBySeqNo("tab_data_content", data.elem.id.substring(data.elem.id.indexOf("_") + 1, data.elem.id.length))
                        .then(function (result) {
                            return result;
                        });

                    //获取商品信息
                    var goodinfo = getGoodInfoById(goodCode);

                    // //获取税率
                    // if (taxRate == null || taxRate <= 0) {
                    //     taxRate = getTaxRate();
                    // }
                    //get商品信息 goodInfo
                    var gooddata = {
                        "seqNo": rowdata.seqNo,
                        "goodCode": data.value,
                        "varietyCode": goodinfo.varietyCode,
                        "varietyName": goodinfo.varietyName,
                        "standardName": goodinfo.standardName,
                        "unit": goodinfo.unit
                        // "inTaxRate": taxRate
                    };

                    var isClear = false;
                    if (data.value == null || data.value.trim().length === 0) {
                        var rowid = gooddata.seqNo;
                        gooddata = {};
                        gooddata['seqNo'] = rowid;
                        isClear = true;
                    }

                    //对商品信息更新赋值
                    updateRowItem("tab_data_content", gooddata, isClear);
                });

                /**
                 * 监听按钮提交事件
                 * @type {{submit: active.confirm, cancel: active.cancel}}
                 */
                var active = {
                    verfyPass: function verfyPass() {
                        // var data = table.cache["tab_data_content"];
                        // var newdata = trimAllArray(data);

                        var request = {
                            stockId: $('#txt_stock_id').val()
                        };
                        // var reqBody = (JSON.stringify(request));

                        $.ajax({
                            type: "POST",
                            url: "/stor/stockin/verfyPass",
                            // contentType: 'application/json',
                            // dataType: 'json',//服务端返回数据类型
                            data: request,
                            async: false,
                            success: function (data) {
                                if (data.rspCode == 'RSP000000') {
                                    layer.msg("审核入库单成功,订单编号:" + data.data);
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index);

                                    parent.reloadTable();
                                    return;
                                } else {
                                    layer.msg("审核入库单失败:" + data.rspMsg);
                                    return;
                                }
                            },
                            error: function (data) {
                                console.log("系统异常:" + data);
                                layer.msg("系统异常,请联系管理员");
                                return;
                            }
                        });
                    },
                    verfyNopass: function verfyNopass() {
                        var request = {
                            stockId: $('#txt_stock_id').val()
                        };

                        $.ajax({
                            type: "POST",
                            url: "/stor/stockin/verfyNopass",
                            // contentType: 'application/json',
                            // dataType: 'json',//服务端返回数据类型
                            data: request,
                            async: false,
                            success: function (data) {
                                if (data.rspCode == 'RSP000000') {
                                    layer.msg("审核不通过入库单成功,订单编号:" + data.data);
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index);

                                    parent.reloadTable();
                                    return;
                                } else {
                                    layer.msg("审核不通过入库单失败:" + data.rspMsg);
                                    return;
                                }
                            },
                            error: function (data) {
                                console.log("系统异常:" + data);
                                layer.msg("系统异常,请联系管理员");
                                return;
                            }
                        });
                    }
                };
                form.on('submit', function (data) {
                    var elem = data.elem;
                    active[$(this).data("type")].call(this, elem);
                });

                resolve(tableIns);
            });
        }).then(function (result) {
            return result;
        });

        return res;
    };

    async function syncInit(rowdata) {
        //初始编辑页面
        //初始控件
        initGoodsInfo(gooddata);

        await syncInitModule();

        await initTable();

        // 加载table明细数据
        layui.use(["form", "jquery", "table"], function () {
            var form = layui.form, table = layui.table, $ = layui.jquery;

            let wheredata = {stockId: rowdata.stockId};

            table.reload('tab_data_content', {
                limit: 50,
                url: '/stor/stockin/getStockinDetailList',
                where: wheredata
            });

            // console.log("执行入库单明细编辑init");

            console.log("init data:", JSON.stringify(rowdata));
            // $('#sel_stor').val(rowdata.storCode);
            $('#txt_stor_name').val(rowdata.storName);
            // $('#sel_organ').val(rowdata.organCode);
            // $('#sel_stockin_type').val(rowdata.stockType);
            var stockTypeName = '';
            switch (rowdata.stockType) {
                case 1:
                    stockTypeName = '采购入库';
                    break;
                case 2:
                    stockTypeName = '调入入库';
                    break;
                case 3:
                    stockTypeName = '借入入库';
                    break;
                case 4:
                    stockTypeName = '归还入库';
                    break;
                case 5:
                    stockTypeName = '组装入库';
                    break;
                default:
                    stockTypeName = rowdata.stockType;
                    break;
            }
            $('#txt_stockin_type').val(stockTypeName);
            renderDate('date_stockin', rowdata.stockDate);
            // $('#date_stockin').val(rowdata.sourBillType);
            // $('#sel_sour_type').val(rowdata.sourBillType);
            $('#txt_sour_id').val(rowdata.sourBillId);
            $('#txt_digest').val(rowdata.digest);
            $('#txt_stock_id').val(rowdata.stockId);

            form.render();
        });

        async function syncInitModule() {
            var nowdate = moment().format('YYYY-MM-DD');
            var resDate = renderDate('date_stockin', nowdate);

            // var resStor = initStorSelect("sel_stor");
            // var params = {};
            // params["sysCode"] = 22;
            // var resStockType = initCodeTableSelect('sel_stockin_type', "/base/getSysCodeList", params);
            // params = {};
            // params["sysCode"] = 23;
            // var resSysCode = initCodeTableSelect('sel_sour_type', "/base/getSysCodeList", params);

            // 阻塞多任务渲染并发
            // var result = await Promise.all([resDate, resStor, resStockType, resSysCode]);
            // result.forEach(function (currval, index, arr) {
            //     console.log(currval);
            // });

            return "done";
        }
    }
</script>
